package cn.com.enboga.musicbox.utils
{
	import flash.utils.ByteArray;
	
	public class EncodeUtils
	{
		public function EncodeUtils()
		{
		}
		
		/**id3文件转义*/
		public static function EncodeUtf8(str:String):String {
			var oriByteArr:ByteArray = new ByteArray();
			oriByteArr.writeUTFBytes(str);
			var tempByteArr:ByteArray = new ByteArray();
			
			for (var i:int = 0; i<oriByteArr.length; i++) {
				if (oriByteArr[i] == 194) {
				tempByteArr.writeByte(oriByteArr[i+1]);
				i++;
				} else if (oriByteArr[i] == 195) {
					tempByteArr.writeByte(oriByteArr[i+1] + 64);
					i++;
				} else {
					tempByteArr.writeByte(oriByteArr[i]);
				}
			}
			tempByteArr.position = 0;
			
			var resultStr:String = tempByteArr.readMultiByte(tempByteArr.bytesAvailable,"chinese");
			trace(resultStr);
			return resultStr;
		}
		
		/** 判断是否为UTF8编码  */
		public static function isUtf(str:String):Boolean {
			var b64:String = escape(str);
			//trace(b64);
			var bs:Array = b64.split("%");
			//trace(bs);
			var utfNum:int = 0;
			var gbkNum:int = 0;
			for(var i:int=0; i<bs.length; i++){
				if(bs[i].length == 5){
					utfNum++;
				}else if(bs[i].length == 2){
					gbkNum++;
				}
			}
			if(utfNum > gbkNum){
				return true;
			}
			
			return false;
		}
		
		/** 中文处理  */
		public static function toUtf8(str:String):String {
			var temp:String = str; 
			if(temp!=null && temp!="" && !isUtf(temp)){
				temp = EncodeUtf8(temp);
			}
							
			return temp;
		}
	}
}